package com.horizon.cloud.standard.config;

import cn.hutool.db.Session;
import com.horizon.cloud.common.constants.SessionConstants;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class FeignConfiguration implements RequestInterceptor {

    //配置rpc时，请求头部与参数
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //取得请求的上下文属性
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();

        if (null == attributes) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        //获取令牌
        String token = request.getHeader(SessionConstants.AUTHORIZATION_HEAD);
        if (null != token) {
            //JWT进行加密认证的流程中，最终会把header(alg, typ)+payload(username...)
            //+signature，加上Bearer前缀形成Bearer认证,放在request的token中
            token = StringUtils.removeStart(token, "Bearer");
            requestTemplate.header(SessionConstants.AUTHORIZATION_HEAD,
                    new String[]{token});
            String userIdentifier = request.getHeader(SessionConstants.USER_IDENTIFIER);
            if (null != userIdentifier) {
                requestTemplate.header(SessionConstants.USER_IDENTIFIER,
                        new String[] {userIdentifier});
            }
        }
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        //Feign日志等级level
        return Logger.Level.NONE;
    }
}
